
<template>
  <div class="app-container">
      <div class="title-wrapper">车辆年审管理</div>
      <div class="page-main">
      <div shadow="never" class="search-wrapper" v-permission="['annualaudit-search']">
        <div class="search-main">
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="carNo" label="车牌号">
              <el-input v-model="searchData.carNo" placeholder="请输入车牌号" clearable/>
            </el-form-item>
          </el-form>
        </div>
        <div class="search-btn">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>
      <div class="toolbar-wrapper">
          <el-button type="primary" v-permission="['annualaudit-add']" @click="handleAdd">新增</el-button>
      </div>

      <div v-loading="loading"  class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column sortable prop="carNo" label="车牌号"  />
          <el-table-column sortable prop="expireDate" label="年审到期日"  />
          <el-table-column sortable prop="price" label="费用"  />
          <el-table-column sortable prop="opaName" label="经办人"  />
          <el-table-column sortable prop="opaDate" label="经办日期"  />
          <el-table-column sortable prop="manageName" label="车辆管理员"  />
          <el-table-column fixed="right" label="操作" width="150" >
            <template #default="scope">
              <el-button type="primary" v-permission="['annualaudit-edit']" text size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" v-permission="['annualaudit-del']" text size="small" @click="handleoneDelete(deleteCarAnnualReviewById, scope.row.carAnnualReviewId,  `${scope.row.carNo}的车辆年审数据`)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  <gm-dialog v-if="dialogVisible"
    ref="dialogRef"
    title="新增/编辑车辆年审"
    @cancel="closeHandle"
    @comfirm="successHandle">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="left">
      <el-form-item prop="carId" label="车辆">
        <carSelect v-model="form.carId" :multiple="false" width="100%" @change="handleChange"></carSelect>
      </el-form-item>
      <el-form-item  prop="price" label="费用">
        <el-input v-model="form.price" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="opaName" label="经办人">
        <el-input v-model="form.opaName" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="opaDate" label="经办日期">
        <el-date-picker
          v-model="form.opaDate"
          type="date"
          placeholder="请选择"
          style="width:100%;"
          format="YYYY-MM-DD" value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item prop="manageName" label="车辆管理员">
        <el-input v-model="form.manageName" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="expireDate" label="年审到期日">
        <el-date-picker
          v-model="form.expireDate"
          type="date"
          placeholder="请选择"
          style="width:100%;"
          format="YYYY-MM-DD" value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="附件" prop="pics">
        <el-upload
        ref="fileUploadBtn"
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload">
          <el-icon class="upload-img-action"><Plus /></el-icon>
        </el-upload>
        <div class="form-value-flex" v-if="form.pics&&form.pics.length>0">
          <uploadImage v-for="item in form.pics" :src="item" @del="handleUploadDel(item)" class="upload-img-image" />
        </div>
      </el-form-item>
      <el-form-item prop="notes" label="备注">
        <el-input v-model="form.notes" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" placeholder="请输入" />
      </el-form-item>


    </el-form>
  </gm-dialog>
</template>
<script lang="ts" setup>
  import { ref, watch,reactive,nextTick } from "vue"
  import { type FormInstance, ElMessage, ElMessageBox,type FormRules } from "element-plus"
  import { getCarAnnualReviewList, deleteCarAnnualReviewById,saveOrUpdateCarAnnualReview,getCarAnnualReviewDetails } from "@/api/vehicle/carAnnualReview"
  import { usePagination } from "@/hooks/usePagination"
  import useTable from '@/hooks/useTable'
  import gmDialog from '@/components/Dialog/index.vue'
  import useForm from '@/hooks/useForm'
  import { cloneDeep } from "lodash-es"
  import carSelect from '@/components/carSelect/index.vue'
  import useFile from '@/hooks/useFile'


  const loading = ref<boolean>(false)
  const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
  const tableData = ref<any>([])
  const dialogVisible = ref<boolean>(false)
    const searchFormRef = ref<FormInstance | null>(null)
  const searchData = reactive<any>({})

  const form = ref<any>({})
  const formRef = ref<FormInstance>()
  const dialogRef = ref<InstanceType<typeof gmDialog>>()

    const { beforeUpload, uploadUrl, uploadImage } = useFile({ maxSize: 10, fileType: 'image' })
    let fileUploadBtn =ref<any>()

  const rules: FormRules = {
    carId: [
      { required: true, message: '请输入车辆', trigger: 'change' },
    ],
    carNo: [
      { required: true, message: '请输入车牌号', trigger: 'change' },
    ],
    // price: [
    //   { required: true, message: '请输入费用', trigger: 'change' },
    //   { pattern: /^\d+(\.\d+)?$/, message: '请输入数字', trigger: 'change' }
    // ],
    opaName: [
      { required: true, message: '请输入经办人', trigger: 'change' },
    ],

    opaDate: [
      { required: true, message: '请输入经办日期', trigger: 'change' },
    ],
    manageName: [
      { required: true, message: '请输入车辆管理员', trigger: 'change' },
    ],
    expireDate: [
      { required: true, message: '请输入年审到期日', trigger: 'change' },
    ],
    pics: [
      { required: true, message: '请输入附件', trigger: 'change' },
    ],
  }



  const getTableData = () => {
    loading.value = true
    getCarAnnualReviewList({
      ...paginationData,
      ...searchData
    }).then((res: any) => {
      paginationData.total = res.totalCount
      tableData.value = res.data
    }).catch(() => {
      tableData.value = []
    }).finally(() => {
      loading.value = false
    })
  }

  const { handleSelectionChange,handleoneDelete } = useTable({getList:getTableData})

  const handleUpdate = (row: any) => {
    getCarAnnualReviewDetails({id:row.carAnnualReviewId}).then((res: any) => {
      form.value = res
      nextTick(()=>{
        form.value.carId =res.carId
        form.value.pics = res.pic ? res.pic.split(',') : []
      })
      dialogVisible.value = true
    }).catch(() => {

    }).finally(() => {
      loading.value = false
    })

  }

  const handleAdd = () => {
    form.value = {
      pics:[]
    }
    dialogVisible.value = true
  }

  //关闭操作框
  const closeHandle = () => {
    dialogVisible.value = false
  }

  //搜索操作
  const handleSearch = () => {
    paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
  }

  //重置搜索表单
  const resetSearch = () => {
    searchFormRef.value?.resetFields()
    handleSearch()
  }

  //操作完成
  const successHandle = () => {
    form.value.pic = form.value.pics.join(',')
    let newForm={
      carAnnualReviewId:form.value.carAnnualReviewId,
      carId:form.value.carId,
      carNo:form.value.carNo,
      price:form.value.price,
      opaName:form.value.opaName,
      pic:form.value.pic,
      opaDate:form.value.opaDate,
      manageName:form.value.manageName,
      expireDate:form.value.expireDate,
      notes:form.value.notes
    }
    handleSubmit(saveOrUpdateCarAnnualReview, formRef.value, newForm, dialogRef.value)

  }
  const handleSubmit = async(api: any, formEl:any,  formData: any, gmRef:any = null) => {
    await formEl.validate((valid: any) => {
      if (!valid) {
        return
      }
      gmRef.setLoading(true)
      api(formData).then((res: any)=>{
        ElMessage({
          message: '操作成功',
          type: 'success',
        })
        dialogVisible.value = false
        getTableData()
        gmRef.setLoading(false)
      }).catch(()=>{
        gmRef.setLoading(false)
      })
    })
  }

  const handleUploadSuccess = (res: any, file: any) => {
    console.log(res,'resresres')
    form.value.pics.push(res.result)
    nextTick(() => {
      // 清空上传组件的文件列表
      if (fileUploadBtn.value) {
        fileUploadBtn.value.clearFiles();
        // 重置 input 的值，确保下次选择相同文件也能触发
        const input = fileUploadBtn.value.$el.querySelector('input[type="file"]') as HTMLInputElement;
        if (input) {
          input.value = '';
        }
      }
    });
  }
  const handleUploadDel = (src: string) => {
    console.log(src, 'sev', form.value.pics)
    form.value.pics = form.value.pics.filter((i) => i !== src)
  }

  const handleChange = (e: any)=>{
    console.log(e,'eeeee')
    form.value.carNo=e.carNo
  }
  watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>
<style lang="scss" scoped>

</style>
